package com.n9.qqonline.sales.product;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ice
 * @since 2019/3/19 11:35
 */
public class MemoryPatentService implements PatentService{
    private static final Map<String, List<Patent>> PATENT_CACHE = new ConcurrentHashMap<>(0);

    @Override
    public List<String> getTags() {
        List<String> list = new ArrayList<>(PATENT_CACHE.size());
        list.addAll(PATENT_CACHE.keySet());
        Collections.sort(list);
        return list;
    }

    @Override
    public List<Patent> getPatentByTag(String tag) {
        if (Objects.isNull(tag)) {
            return new ArrayList<>(0);
        }
        List<Patent> patents = PATENT_CACHE.get(tag);
        if (Objects.isNull(patents)) {
            return new ArrayList<>(0);
        }
        return Collections.unmodifiableList(patents);
    }

    @Override
    public void addPatent(String tag, Patent patent) {
        if (Objects.isNull(tag)) {
            return;
        }
        if (Objects.isNull(patent)) {
            return;
        }
        List<Patent> patents = PATENT_CACHE.get(tag);
        if (Objects.isNull(patents)) {
            patents = Collections.synchronizedList(new ArrayList<>(0));
            PATENT_CACHE.put(tag, patents);
        }
        patents.add(patent);
    }

    @Override
    public void clear() {
        PATENT_CACHE.clear();
    }
}
